<?php
/**
 * Created by PhpStorm.
 * Script Name: Mpfollow.php
 * Create: 2023/1/11 9:08
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\MpFollow as FollowM;
use plugin\wechat\app\model\MpTask;
use plugin\wechat\app\service\MpTag as TagService;
use plugin\wechat\app\service\MpTask as TaskService;
use think\facade\Db;
use Support\Request;
use plugin\wechat\app\service\MpFollow as FollowService;
use plugin\wechat\app\service\MpFollowBlack as BlackService;

class Mpfollow extends MpBase
{
    /**
     * @var FollowM
     */
    protected $model;
    /**
     * @var MpTask
     */
    private MpTask $taskM;

    public function __construct()
    {
        parent::__construct();
        $this->model = new FollowM();
        $this->taskM = new MpTask();
    }

    /**
     * 粉丝列表
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request)
    {
        $mp_info = $request->mpInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['mp_id', '=', $mp_info['id']]
            ];
            !empty($post_data['search_key']) && $where[] = [
                'nickname|openid|remark', 'like', '%' . $post_data['search_key'] . '%'
            ];
            !empty($post_data['tag']) && $where[] = [
                'tagid_list', 'like', '%"' . $post_data['tag'] . '"%'
            ];
            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '根据昵称/备注/openid搜索'],
            ['type' => 'select', 'name' => 'tag', 'title' => '标签', 'options' => TagService::getTagIdToName($mp_info, true)]
        ])
            ->addTopButton('self', ['class'=>'layui-btn-normal','text' => '同步粉丝数据', 'href' => url('pullpost'), 'data-ajax' => true, 'data-confirm' => true])
            ->addTableColumn(['title' => 'openid', 'field' => 'openid',  'minWidth' => 100])
            ->addTableColumn(['title' => '昵称', 'field' => 'nickname', 'minWidth' => 100])
            ->addTableColumn(['title' => '头像', 'field' => 'headimgurl', 'type' => 'picture', 'minWidth' => 100])
            ->addTableColumn(['title' => '备注', 'field' => 'remark', 'minWidth' => 70])
            ->addTableColumn(['title' => '关注状态', 'field' => 'subscribe', 'type' => 'enum','options' => [0 => '取消关注', 1 => '已关注'], 'minWidth' => 100])
            ->addTableColumn(['title' => '关注时间', 'field' => 'subscribe_time', 'type' => 'datetime', 'minWidth' => 180])
            ->addTableColumn(['title' => '操作', 'minWidth' => 160, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete', ['text' => '拉入黑名单', 'href' => url('blackPost', ['openid' => '__data_openid__']), 'data-ajax'=>true, 'data-confirm' => '确认拉黑吗？']);

        return $builder->show();
    }

    /**
     * 拉黑用户
     * @param Request $request
     * @return \support\Response
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function blackPost(Request $request){
        if($request->isPost()){
            $mp_info = $request->mpInfo;
            $openid = input('openid', '');
            if(! $data = $this->model->where([$this->tenantWhere(), $this->mpIdWhere()])->where('openid', $openid)->find()){
                return $this->error('数据不存在');
            }
            if(is_string($res = BlackService::block($openid, $mp_info))){
                return $this->error($res);
            }
            return $this->success('操作成功！');
        }
    }

    /**
     * 粉丝同步
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function pullPost(){
        if($task = $this->taskM->where('mp_id', $this->mpInfo['id'])
            ->where('module', TaskService::MODULE_PULL_FOLLOW)
            ->find()){
            $this->taskM->update(['id' => $task['id'], 'status' => TaskService::STATUS_RUNNING]);
        }else{
            $this->taskM->createOne([
                'mp_id' => $this->mpInfo['id'],
                'company_id' => TenantService::getCompanyId(),
                'status' => TaskService::STATUS_RUNNING,
                'module' => TaskService::MODULE_PULL_FOLLOW
            ]);
        }
        return $this->success('正在后台同步，您可以继续进行其他操作！');
    }

    /**
     * 编辑粉丝
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(Request $request){
        $mp_info = $request->mpInfo;
        if(! $data = $this->model->where([$this->tenantWhere(), $this->mpIdWhere()])->find(input('id'))){
            return $this->error('数据不存在');
        }
        $tag_list = [];
        if(! is_string($res = TagService::tagList($mp_info))){
            foreach ($res['tags'] as $tag){
                $tag_list[$tag['id']] = $tag['name'];
            }
        }
        if(empty($data['tagid_list'])){
            $data['tagid_list'] = [];
        }else{
            $data['tagid_list'] = json_decode($data['tagid_list'], true);
        }
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savepost'))
            ->addFormItem('id', 'hidden', 'id', '')
            ->addFormItem('openid', 'hidden', 'openid', 'openid')
            ->addFormItem('tagid_list', 'chosen_multi', '标签', '标签', $tag_list)
            ->addFormItem('remark', 'text', '备注', '30字符内', [], ' maxlength=30')
            ->setFormData($data);
        return $builder->show();
    }

    /**
     *
     * @param Request $request
     * @param string $jump
     * @param array $data
     * @return mixed|\support\Response
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function savePost(Request $request, $jump = '', $data = [])
    {
        $mp_info = $request->mpInfo;
        $data = $request->post();
        if(! $follow = $this->model->where([$this->tenantWhere(), $this->mpIdWhere()])->find(input('id'))){
            return $this->error('非法操作!');
        }
        if($follow['tagid_list']){
            $follow['tagid_list'] = json_decode($follow['tagid_list']);
        }else{
            $follow['tagid_list'] = [];
        }
        Db::startTrans();
        try {
            $data['tagid_list'] = $data['tagid_list'] ? explode(',', $data['tagid_list']) : [];
            if(!empty($data['tagid_list'])){
                $res = FollowService::tagAdd($data['openid'], $data['tagid_list'], $mp_info);
                if(is_string($res)){
                    return $this->error($res, '', ['token' => token()]);
                }
            }
            if(!empty($follow['tagid_list']) && $diff = array_diff($follow['tagid_list'], $data['tagid_list'])){
                //需要删除的标签
                $res = FollowService::tagRemove($data['openid'], $diff, $mp_info);
                if(is_string($res)){
                    return $this->error($res, '', ['token' => token()]);
                }
            }
            $data['tagid_list'] = json_encode($data['tagid_list']);
            if(!empty($data['remark'])){
                $res = FollowService::remark($data['openid'], $data['remark'], $mp_info);
                if(is_string($res)){
                    return $this->error($res, '', ['token' => token()]);
                }
            }

            $this->model->update($data);
            Db::commit();
            return $this->success('操作成功！');
        }catch (\Exception $e){
            Db::rollback();
            return $this->error("操作失败：" . $e->getMessage(), '', ['token' => token()]);
        }
    }
}